﻿using System.Security.Cryptography; 

namespace Agile.Infra.Core.Agile.Security
{
    public static class AESHelper
    {
        //配置的密钥
        private static string _defaultAESKey = "IiDLCxOUsjJ+jRzUe0RcpA==";

        /// <summary>
        /// 加密（返回Base64字符串）
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Encrypt(string plainText, string key = null)
        {
            if (key.IsNullOrEmpty()) key = _defaultAESKey;
            var keyArray = Encoding.UTF8.GetBytes(key);
            return Encrypt(plainText, keyArray);
        }
        /// <summary>
        /// 加密（返回Base64字符串）
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Encrypt(string plainText, byte[] key)
        {
            using var aes = Aes.Create();
            aes.Key = key;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.GenerateIV(); // 自动生成随机的IV[5,8](@ref)

            var encryptor = aes.CreateEncryptor();
            using var ms = new MemoryStream();
            // 将IV写入密文头部
            ms.Write(aes.IV, 0, aes.IV.Length);

            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                var data = Encoding.UTF8.GetBytes(plainText);
                cs.Write(data, 0, data.Length);
            }
            return Convert.ToBase64String(ms.ToArray());
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decrypt(string cipherText, string key = null)
        {
            if (key.IsNullOrEmpty()) key = _defaultAESKey;
            var keyArray = Encoding.UTF8.GetBytes(key);
            return Decrypt(cipherText, keyArray);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decrypt(string cipherText, byte[] key)
        {
            var fullCipher = Convert.FromBase64String(cipherText);
            using var aes = Aes.Create();
            aes.Key = key;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            // 从密文中提取IV（前16字节）
            aes.IV = fullCipher.Take(16).ToArray();
            var cipherData = fullCipher.Skip(16).ToArray();

            var decryptor = aes.CreateDecryptor();
            using var ms = new MemoryStream(cipherData);
            using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
            using var sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// 生成合规密钥（128/192/256位）
        /// </summary>
        /// <param name="keySize"></param>
        /// <returns></returns>
        public static byte[] GenerateKey(int keySize = 256)
        {
            using var rng = RandomNumberGenerator.Create();
            var key = new byte[keySize / 8];
            rng.GetBytes(key);
            return key;
        }

        public static string GenerateStrKey(int keySize = 128)
        {
            var keyBytes = GenerateKey(keySize);

            return Convert.ToBase64String(keyBytes);
        }
    }
}
